package com.ascent.client.ui;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.*;
import java.io.IOException;
import java.util.Objects;
import java.util.regex.Pattern;

import javax.swing.*;

import com.ascent.bean.User;
import com.ascent.client.util.UserDataClient;

/**
 * 新增用户窗体
 */
@SuppressWarnings("serial")
public class AddUserFrame extends JFrame {
    private JTextField userText;
    private JTextField password;
    private JComboBox<String> authComBox;
    private JLabel tip;

    private UserDataClient userDataClient;
    boolean isLegal = false;

    /**
     * 默认构造方法，初始化新增用户窗体
     */
    public AddUserFrame() {
        this.setTitle("新增用户");

        Container container = this.getContentPane();
        container.setLayout(new BorderLayout());

        JPanel addUserPanel = new JPanel();
        JPanel buttonPanel = new JPanel();

        JLabel userLabel = new JLabel("用户帐号：");
        JLabel passwordLabel = new JLabel("用户密码：");
        JLabel authLabel = new JLabel("用户权限：");

        userText = new JTextField(15);
        password = new JTextField(15);

        String[] options = {"普通用户", "管理员"};
        authComBox = new JComboBox<>(options);


        JButton submitButton = new JButton("提交");
        JButton exitButton = new JButton("退出");

        addUserPanel.add(userLabel);
        addUserPanel.add(new JScrollPane(userText));
        addUserPanel.add(passwordLabel);
        addUserPanel.add(new JScrollPane(password));
        addUserPanel.add(authLabel);
        addUserPanel.add(new JScrollPane(authComBox));

        buttonPanel.add(submitButton);
        buttonPanel.add(exitButton);

        setResizable(false);
        setSize(260, 180);
        setLocation(300, 100);

        JPanel tipPanel = new JPanel();

        tip = new JLabel();

        tipPanel.add(tip);

        container.add(BorderLayout.CENTER, addUserPanel);
        container.add(BorderLayout.NORTH, tip);
        container.add(BorderLayout.SOUTH,buttonPanel);

        exitButton.addActionListener(new ExitActionListener());
        submitButton.addActionListener(new AddUserActionAddListener());
        userText.addFocusListener(new UsernameFocusListener());
        password.addFocusListener(new PasswordFocusListener());

        this.addWindowListener(new WindowCloser());
        this.addWindowFocusListener(new WindowFocusListener() {// 设置父窗口
            public void windowGainedFocus(WindowEvent e) {
            }
            public void windowLostFocus(WindowEvent e) {
                e.getWindow().toFront();
            }
        });
        try {
            userDataClient = new UserDataClient();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    /**
     * 退出按钮事件监听
     * @author ascent
     */
    class ExitActionListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            setVisible(false);
            dispose();
        }
    }

    /**
     * 提交按钮事件监听
     * @author ascent
     */
    class AddUserActionAddListener implements ActionListener {
        public void actionPerformed(ActionEvent arg0) {
            if (!isLegal){
                tip.setText("信息不合规范，请重新填写");
                return;
            }
            // 获取填写的信息
            String username = userText.getText();
            String pass = password.getText();
            int auth;
            if (Objects.equals((String) authComBox.getSelectedItem(), "管理员")){
                auth = 1;
            }else{
                auth = 0;
            }
            User newUser = new User(username,pass,auth);
            //向服务器发生请求
            boolean bo = userDataClient.addUser(newUser);
            if (bo) {
                tip.setText("新增用户成功！");
            } else {
                tip.setText("用户名已存在！");
            }
        }
    }
    /**
     * 用户名的事件监听器
     */
    class UsernameFocusListener implements FocusListener {

        @Override
        public void focusGained(FocusEvent e) {

        }

        @Override
        public void focusLost(FocusEvent e) {
            //使用正则表达式进行表单验证
            String text = String.valueOf(userText.getText()).trim();
            String regex = "^[a-zA-Z][a-zA-Z0-9]{3,11}$";
            Pattern pattern = Pattern.compile(regex);
            boolean isValid = pattern.matcher(text).matches();

            if (text.equals("")){
                tip.setText("用户名不能为空！");
                isLegal = false;
            }else if (!isValid){
                tip.setText("由字母开头，包含字母与数字,长度4-12");
                isLegal = false;
            } else{
                tip.setText("");
                isLegal = true;
            }
        }
    }

    /**
     * 密码输入窗口事件监听器
     */
    class PasswordFocusListener implements FocusListener{

        @Override
        public void focusGained(FocusEvent e) {

        }

        @Override
        public void focusLost(FocusEvent e) {
            //使用正则表达式进行表单验证
            String passwordText = String.valueOf(password.getText()).trim();
            String regex = "^[a-zA-Z0-9]{6,16}$";
            Pattern pattern = Pattern.compile(regex);
            boolean isValid = pattern.matcher(passwordText).matches();
            if (passwordText.equals("")){
                tip.setText("密码不能为空！");
                isLegal = false;
            } else if (!isValid){
                tip.setText("字母数字的组合,长度6-12");
                isLegal = false;
            }else{
                tip.setText("");
                isLegal = true;
            }
        }
    }
    /**
     * "关闭窗口"事件处理内部类
     * @author ascent
     */
    class WindowCloser extends WindowAdapter {
        public void windowClosing(WindowEvent e) {
            setVisible(false);
            dispose();
        }
    }
}
